﻿namespace Utility1
{
    using Microsoft.Win32;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Caching;
    using System.Xml.Linq;
    using System.Xml.Serialization;

    public static class Utils
    {
        public static string ArrayToString(IList array, string delimeter)
        {
            string str = "";
            for (int i = 0; i < array.Count; i++)
            {
                if (array[i] is IList)
                {
                    str = str + ArrayToString((IList) array[i], delimeter);
                }
                else
                {
                    str = str + array[i];
                }
                if (i != (array.Count - 1))
                {
                    str = str + delimeter;
                }
            }
            return str;
        }

        public static string ArrayToString<T>(List<T> array, string properties, string delimeter)
        {
            string str = "";
            for (int i = 0; i < array.Count; i++)
            {
                Type type = typeof(T);
                str = str + type.GetProperty(properties).GetValue(array[i], null).ToString();
                if (i != (array.Count - 1))
                {
                    str = str + delimeter;
                }
            }
            return str;
        }

        public static string CombineUrl(string baseUrl, string relativeUrl)
        {
            UriBuilder builder = new UriBuilder(baseUrl);
            Uri result = null;
            if (!Uri.TryCreate(builder.Uri, relativeUrl, out result))
            {
                throw new ArgumentException("Unable to combine specified url values");
            }
            return result.ToString();
        }

        public static string ConvertIdsToSting(List<int> ids)
        {
            StringBuilder builder = new StringBuilder();
            if (null != ids)
            {
                foreach (int num in ids)
                {
                    if (builder.Length > 0)
                    {
                        builder.Append(',');
                    }
                    builder.Append(num.ToString());
                }
            }
            return builder.ToString();
        }

        public static T ConvertNullableFromString<T>(string param)
        {
            NullableConverter converter = new NullableConverter(typeof(T));
            return (T) converter.ConvertFromString(param);
        }

        public static XElement ConverToXElement(string xml)
        {
            using (StringReader reader = new StringReader(xml))
            {
                return XElement.Load(reader);
            }
        }

        public static string ConvertToFullTextSearchString(string search)
        {
            if (string.IsNullOrEmpty(search))
            {
                return search;
            }
            search = search.Replace("'", "").Replace("-", "").Replace(",", "").Replace("*", "");
            List<string> list = new List<string>();
            int startIndex = -1;
            int num2 = 0;
            for (int i = 0; i < search.Length; i++)
            {
                switch (search[i])
                {
                    case ' ':
                    {
                        if (-1 == startIndex)
                        {
                            if (num2 < i)
                            {
                                list.Add(search.Substring(num2, i - num2));
                            }
                            num2 = i + 1;
                        }
                        continue;
                    }
                    case '!':
                    {
                        continue;
                    }
                    case '"':
                    {
                        if (startIndex < 0)
                        {
                            break;
                        }
                        list.Add(search.Substring(startIndex, (i - startIndex) + 1));
                        startIndex = -1;
                        num2 = i + 1;
                        continue;
                    }
                    default:
                    {
                        continue;
                    }
                }
                if (num2 < i)
                {
                    list.Add(search.Substring(num2, i - num2));
                }
                startIndex = i;
            }
            if (startIndex >= 0)
            {
                list.Add(search.Substring(startIndex) + "\"");
            }
            else if (num2 < search.Length)
            {
                list.Add(search.Substring(num2));
            }
            return string.Join(",", list.ToArray());
        }

        public static string ConvertToUnSign(string text)
        {
            int num;
            char ch;
            for (num = 0x21; num < 0x30; num++)
            {
                ch = (char) num;
                text = text.Replace(ch.ToString(), "");
            }
            for (num = 0x3a; num < 0x41; num++)
            {
                ch = (char) num;
                text = text.Replace(ch.ToString(), "");
            }
            for (num = 0x5b; num < 0x61; num++)
            {
                text = text.Replace(((char) num).ToString(), "");
            }
            for (num = 0x7b; num < 0x7f; num++)
            {
                text = text.Replace(((char) num).ToString(), "");
            }
            text = text.Replace(" ", "-");
            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
            string input = text.Normalize(NormalizationForm.FormD);
            return regex.Replace(input, string.Empty).Replace('đ', 'd').Replace('Đ', 'D');
        }

        public static decimal ChangeBadConversionToDefault(string param, decimal defaultValue)
        {
            decimal result = defaultValue;
            decimal.TryParse(param, out result);
            return result;
        }

        public static int ChangeBadConversionToDefault(string param, int defaultValue)
        {
            int result = defaultValue;
            int.TryParse(param, out result);
            return result;
        }

        public static bool CheckParameterExist(string param)
        {
            return (null != HttpContext.Current.Request.QueryString[param]);
        }

        public static void EnsurePathExist(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        public static string EscapeSeparators(string param)
        {
            return EscapeSeparators(param, new char[] { '\\', ',', ';' });
        }

        public static string EscapeSeparators(string param, params char[] separators)
        {
            if (!string.IsNullOrEmpty(param))
            {
                foreach (char ch in separators)
                {
                    param = param.Replace(ch.ToString(), string.Format(@"\{0}", ch));
                }
            }
            return param;
        }

        public static string FormatPhoneForDisplay(string phone)
        {
            if (!string.IsNullOrEmpty(phone))
            {
                phone = Regex.Replace(phone, @"[^\d]", "");
                phone = phone.Insert(0, "(");
                if (phone.Length <= 4)
                {
                    return phone;
                }
                phone = phone.Insert(4, ")");
                if (phone.Length > 8)
                {
                    phone = phone.Insert(8, "-");
                }
            }
            return phone;
        }

        public static string FormatTimeSpan(TimeSpan ts)
        {
            return string.Format("{0}{1:00}:{2:00}:{3:00}", new object[] { (ts.Days == 0) ? "" : (ts.Days.ToString() + "."), ts.Hours, ts.Minutes, ts.Seconds });
        }

        public static T FromXml<T>(string xml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringReader textReader = new StringReader(xml);
            return (T) serializer.Deserialize(textReader);
        }

        public static object FromXml(Type type, string xml)
        {
            XmlSerializer serializer = new XmlSerializer(type);
            StringReader textReader = new StringReader(xml);
            return serializer.Deserialize(textReader);
        }

        public static string GetAppName()
        {
            return Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]);
        }

        public static byte[] GetBitsFromSteam(Stream fs, int size)
        {
            byte[] buffer = new byte[size];
            fs.Read(buffer, 0, size);
            return buffer;
        }

        public static byte[] GetData(Stream fs)
        {
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, (int) fs.Length);
            return buffer;
        }

        public static DateTime GetDateTimeParameter(string param, DateTime defaultValue)
        {
            DateTime result = defaultValue;
            string str = HttpContext.Current.Request.QueryString[param];
            if (!string.IsNullOrEmpty(str))
            {
                DateTime.TryParse(HttpUtility.UrlDecode(str), out result);
            }
            return result;
        }

        public static List<KeyValuePair<string, int>> GetEnumNameValueList(Type enumType)
        {
            List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
            foreach (int num in Enum.GetValues(enumType))
            {
                list.Add(new KeyValuePair<string, int>(Enum.GetName(enumType, num), num));
            }
            return list;
        }

        public static string GetInstallPath()
        {
            string directoryName = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
            if (string.IsNullOrEmpty(directoryName))
            {
                return Directory.GetCurrentDirectory();
            }
            return directoryName;
        }

        public static int GetIntParameter(string param)
        {
            string str = HttpContext.Current.Request.QueryString[param];
            if (string.IsNullOrEmpty(str))
            {
                throw new ApplicationException(string.Format("{0} is required parameter", param));
            }
            return int.Parse(str);
        }

        public static int GetIntParameter(string param, int defaultValue)
        {
            int result = defaultValue;
            string str = HttpContext.Current.Request.QueryString[param];
            if (!string.IsNullOrEmpty(str))
            {
                int.TryParse(str, out result);
            }
            return result;
        }

        public static decimal? GetNullableDecimalParameter(string param)
        {
            decimal num;
            string str = HttpContext.Current.Request.QueryString[param];
            if (!(string.IsNullOrEmpty(str) || !decimal.TryParse(str, out num)))
            {
                return new decimal?(num);
            }
            return null;
        }

        public static int? GetNullableIntParameter(string param)
        {
            int num;
            string str = HttpContext.Current.Request.QueryString[param];
            if (!(string.IsNullOrEmpty(str) || !int.TryParse(str, out num)))
            {
                return new int?(num);
            }
            return null;
        }

        public static List<NameValueContainer> GetNumbers(int from, int to)
        {
            List<NameValueContainer> list = new List<NameValueContainer>();
            for (int i = from; i <= to; i++)
            {
                string name = i.ToString();
                list.Add(new NameValueContainer(name, i.ToString()));
            }
            return list;
        }

        public static string GetParameter(string param)
        {
            string str = HttpContext.Current.Request.QueryString[param];
            if (null == str)
            {
                throw new ApplicationException(string.Format("{0} is required parameter", param));
            }
            return str;
        }

        public static string GetParameter(string param, string defaultValue)
        {
            string str = HttpContext.Current.Request.QueryString[param];
            if (null != str)
            {
                return str;
            }
            return defaultValue;
        }

        public static string GetPropertyDescName(Type t)
        {
            int index = t.Name.IndexOf("_");
            return t.Name.Substring(index + 1);
        }

        public static List<Type> GetProviders(string searchPatch, Type providerType)
        {
            List<Type> list = new List<Type>();
            string path = HttpContext.Current.Server.MapPath("~/bin");
            foreach (string str2 in Directory.GetFiles(path, searchPatch, SearchOption.TopDirectoryOnly))
            {
                Assembly assembly = Assembly.Load(Path.GetFileNameWithoutExtension(str2));
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsSubclassOf(providerType))
                    {
                        list.Add(type);
                    }
                }
            }
            return list;
        }

        public static bool GetRegisteredApplication(string ParamFileName, out string AppName, out string ShellAppName)
        {
            AppName = string.Empty;
            ShellAppName = string.Empty;
            string extension = Path.GetExtension(ParamFileName);
            string str2 = null;
            string str3 = null;
            RegistryKey classesRoot = null;
            RegistryKey key2 = null;
            RegistryKey key3 = null;
            int length = 0;
            try
            {
                try
                {
                    classesRoot = Registry.ClassesRoot;
                    key2 = classesRoot.OpenSubKey(extension);
                    str2 = key2.GetValue(null).ToString();
                    key2.Close();
                }
                catch
                {
                    return false;
                }
                try
                {
                    key3 = classesRoot.OpenSubKey(str2 + @"\shell\open\command");
                    str3 = key3.GetValue(null).ToString();
                    key3.Close();
                }
                catch
                {
                    return false;
                }
                length = str3.IndexOf(" %1");
                if (length > 0)
                {
                    str3 = str3.Substring(0, length);
                    AppName = str3;
                    str3 = string.Concat(new object[] { str3, " ", Convert.ToChar(0x22), ParamFileName, Convert.ToChar(0x22) });
                    ShellAppName = str3;
                }
                else
                {
                    AppName = str3;
                    ShellAppName = string.Concat(new object[] { str3, " ", Convert.ToChar(0x22), ParamFileName, Convert.ToChar(0x22) });
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static string getScmplit(string name, string pathTree)
        {
            string str = string.Empty;
            int num = pathTree.Count<char>(i => i.Equals('.')) - 1;
            for (int j = 0; j < num; j++)
            {
                str = str + ".   ";
            }
            object obj2 = str;
            return string.Concat(new object[] { obj2, " |", num, "| ", name });
        }

        public static string GetSorted(List<int> values)
        {
            values.Sort();
            StringBuilder builder = new StringBuilder();
            foreach (int num in values)
            {
                if (builder.Length > 0)
                {
                    builder.Append(',');
                }
                builder.Append(num);
            }
            return builder.ToString();
        }

        public static string GetUrlableString(string s)
        {
            return Regex.Replace(s, @"[^\w- ,]", " ");
        }

        public static string GetUserName()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return HttpContext.Current.User.Identity.Name;
            }
            return HttpContext.Current.Session.SessionID;
        }

        public static object GetValueProperties(object o, string property)
        {
            object obj2 = null;
            PropertyInfo info = o.GetType().GetProperty(property);
            if (info != null)
            {
                obj2 = info.GetValue(o, null);
            }
            return obj2;
        }

        public static bool IsAdmin()
        {
            return HttpContext.Current.User.IsInRole("Administrator");
        }

        public static bool IsValidateDBTime(DateTime time)
        {
            return ((Constant.DB.DBDateTimeMinValue < time) && (time < Constant.DB.DBDateTimeMaxValue));
        }

        public static int[] ParseIds(string idsString)
        {
            return ParseIds(idsString, new char[] { ',' });
        }

        public static int[] ParseIds(string idsString, params char[] separator)
        {
            string[] strArray = idsString.Split(separator);
            int[] numArray = new int[strArray.Length];
            for (int i = 0; i < strArray.Length; i++)
            {
                numArray[i] = int.Parse(strArray[i]);
            }
            return numArray;
        }

        public static string ReplaceTokens(string template, NameValueCollection tokens)
        {
            foreach (string str in tokens.Keys)
            {
                string newValue = tokens[str];
                template = template.Replace(string.Format("%{0}%", str), newValue);
            }
            return template;
        }

        public static decimal Round(decimal d)
        {
            return decimal.Round(d, 2);
        }

        public static decimal? Round(decimal? d)
        {
            if (!d.HasValue)
            {
                return null;
            }
            return new decimal?(Round(d.Value));
        }

        public static void SetValueProperties(object o, string property, object value)
        {
            PropertyInfo info = o.GetType().GetProperty(property);
            if (info != null)
            {
                info.SetValue(o, value, null);
            }
        }

        public static string StringChangeEmptyToNull(string param)
        {
            return (string.IsNullOrEmpty(param) ? null : param);
        }

        public static string ToDBNullString(object param)
        {
            if (null == param)
            {
                return "NULL";
            }
            return param.ToString();
        }

        public static string ToDBNullString(string param)
        {
            if (string.IsNullOrEmpty(param))
            {
                return "NULL";
            }
            return param;
        }

        public static XElement ToXElement(this object o)
        {
            return ConverToXElement(o.ToXml());
        }

        public static string ToXml(this object o)
        {
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            StringWriter writer = new StringWriter();
            serializer.Serialize((TextWriter) writer, o);
            return writer.ToString();
        }

        public static System.Web.Caching.Cache Cache
        {
            get
            {
                HttpContext current = HttpContext.Current;
                if (null == current)
                {
                    return HttpRuntime.Cache;
                }
                return current.Cache;
            }
        }

        public class NameValueContainer
        {
            private string name;
            private string value;

            public NameValueContainer(string name, string value)
            {
                this.name = name;
                this.value = value;
            }

            public string Name
            {
                get
                {
                    return this.name;
                }
            }

            public string Value
            {
                get
                {
                    return this.value;
                }
            }

            
        }

        public static string GetMoneyString(double money)
        {
            return money.ToString("###,###,###,##0.##").Replace(",", " ").Replace(".", ",").Replace(" ", ".");
        }

        public static string GetMoneyStringHost(double money)
        {
            return money.ToString("###.###.###.##0,##").Replace(".", " ").Replace(",", ".").Replace(" ", ",");
        }

        public static DateTime GetLastDayOfMonth(int year, int month)
        {
            return new DateTime(year, month, DateTime.DaysInMonth(year, month));
        }

        public static DateTime GetfirstDayOfMonth(int year, int month)
        {
            return new DateTime(year, month, 1);
        }
        public static string RemoveHtmlTagsUsingRegex(string htmlString)
        {
            var result = Regex.Replace(htmlString, "<.*?>", string.Empty);
            return result;
        }

    }
}

